<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import { useReportHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { CommonUtils } from "@/utils/common";
import ReportFormModal from "./report-form-modal.vue";
import {
  ReportPageResponse, submitProblemApi,
  updateReportApi,
  UpdateReportCommand
} from "@/api/airport/safetyManage/report.api";
import AddFill from "@iconify-icons/ri/add-circle-line";
import ReportDetailModal from "./report-detail-modal.vue";
import ReportForwardModal from "./report-forward-modal.vue";

import Detail from "@iconify-icons/ep/view";
// 引入新图标
import Link from "@iconify-icons/ep/link";
import ModelBuild from "@iconify-icons/ep/setting";

import {Bottom, Top, UserFilled, Right} from '@element-plus/icons-vue';
import {ElIcon, ElMessage, ElMessageBox} from "element-plus";
import {getDeptTree} from "@/api/system/dept";
import {useUserStoreHook} from "@/store/modules/user";
import {message} from "@/utils/message";

// 引入 getInspectionCheckInfoApi 函数
import { getInspectionCheckInfoApi } from "@/api/airport/inspection/inspectionCheck";
// 引入 inspectionCheck-detail-modal 组件
import InspectionCheckDetailModal from "@/views/airport/inspection/inspectionCheck/inspectionCheck-detail-modal.vue";
import ReportSubmitModal from "./report-submit-modal.vue";
import { useRoute, useRouter } from 'vue-router'; // 导入路由相关方法


defineOptions({
  name: "reportList"
});

const { hasAdminPermission } = useUserStoreHook();
// 批量删除权限控制处理函数
const handleBulkDeleteWithPermission = (tableRef) => {
  debugger
  if (hasAdminPermission) {
    handleBulkDelete(tableRef);
  } else {
    ElMessage.warning("您没有部门负责人权限");
  }
};

const tableRef = ref();
const searchFormRef = ref();
const {
  pageLoading,
  columns,
  dataList,
  pagination,
  timeRange,
  defaultSort,
  multipleSelection,
  onSearch,
  resetForm,
  onSortChanged,
  exportAllExcel,
  getReportList,
  handleDelete,
  handleBulkDelete,
  searchFormParams,
  // 新增方法
  linkExistingModel,
  riskModeling,
  decodeBase64withoutLab
} = useReportHook();


const route = useRoute(); // 初始化路由
const router = useRouter(); // 添加路由实例

const submitDialogVisible = ref(false); // 问题提交弹窗显示状态
const submitRow = ref<ReportPageResponse>(); // 问题提交的行数据
const opType = ref<"add" | "update">("add");
const modalVisible = ref(false);
const opRow = ref<ReportPageResponse>();
const forwardDialogVisible = ref(false); // 转发弹窗显示状态
const detailVisible = ref(false);
const detailRow = ref<ReportPageResponse>();
const selectedReportId = ref(0); // 当前选中要转发的 reportId
const forwardRow = ref<ReportPageResponse>(); // 转发的行数据
// 新增变量控制 inspectionCheck 详情弹窗
const inspectionCheckDetailVisible = ref(false);
const inspectionCheckDetailData = ref(null);

// 添加整改通知点击事件处理函数
function handleReformClick(row) {
  if (row.relatedReformCode && row.relatedReformCode !== '') {
    router.push({
      path: '/airport/reform/reformMain/index',
      query: { code: row.relatedReformCode }
    });
  }
}

// 转发处理方法
async function handleForward(row: ReportPageResponse) {
  forwardRow.value = row;
  forwardDialogVisible.value = true;
}


function openDialog(type: "add" | "update", row?: ReportPageResponse) {
  opType.value = type;
  opRow.value = row;
  modalVisible.value = true;
}

// 打开 inspectionCheck 详情弹窗
async function openInspectionCheckDetail(inspectionCheckId: number) {
  try {
    const { data } = await getInspectionCheckInfoApi(inspectionCheckId);
    inspectionCheckDetailData.value = data;
    inspectionCheckDetailVisible.value = true;
  } catch (error) {
    console.error('获取检查项详情失败', error);
    ElMessage.error('获取检查项详情失败，请重试');
  }
}


function openDetail(row: ReportPageResponse) {
  detailRow.value = row;
  if (row.inspectionCheckId) {
    openInspectionCheckDetail(row.inspectionCheckId);
  } else {
    detailVisible.value = true;
  }
}

// 添加重置处理函数
async function handleReset() {
  // 1. 调用原有的重置表单方法
  resetForm(searchFormRef, tableRef);

  // 2. 清除URL中的reportId参数
  if (route.query.reportId) {
    const { reportId, ...otherQuery } = route.query;
    router.replace({
      path: route.path,
      query: Object.keys(otherQuery).length ? otherQuery : undefined
    });
  }

  // 3. 重置后刷新表格数据
  await getReportList();
}



const deptTree = ref([]);


// 获取URL中的reportId参数并设置为查询条件
const reportId = route.query.reportId;
if (reportId) {
  searchFormParams.reportId = Number(reportId);
}

onMounted(async () => {
  try {
    const { data } = await getDeptTree();
    if (data) {
      // 转换数据格式
      const convertDeptTree = (nodes) => {
        return nodes.map(node => ({
          value: node.id,
          label: node.label,
          children: node.children ? convertDeptTree(node.children) : undefined
        }));
      };
      // 若 data 本身是数组，直接转换
      if (Array.isArray(data)) {
        deptTree.value = convertDeptTree(data);
      } else {
        // 若 data 不是数组，将其包裹成数组再转换
        deptTree.value = convertDeptTree([data]);
      }
    }

    // await getReportList(); // 执行查询
  } catch (error) {
    console.error('获取部门树数据失败:', error);
  }
});

async function handleReceive(row: UpdateReportCommand) {
  const userStore = useUserStoreHook();
  const currentDeptId = userStore.currentUserInfo.deptId; // 获取当前用户的部门 ID

  try {
    // 弹出确认提示框
    await ElMessageBox.confirm(
      '确认是否要接收该安全信息？',
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const updateData:UpdateReportCommand = {
      reportId: row.reportId,
      acceptDeptId: currentDeptId,
      status: '1',
    };

    // 调用更新接口
    await updateReportApi(updateData);
    message("接收成功", { type: "success" });
    // 刷新列表
    await getReportList();
  } catch (error) {
    if (error === 'cancel') {
      message("取消接收", { type: "info" });
    } else {
      console.error('接收失败', error);
      message("接收失败，请重试", { type: "error" });
    }
  }
}

// 问题提交处理方法
function handleSubmit(row: ReportPageResponse) {
  submitRow.value = row;
  submitDialogVisible.value = true;
}



</script>

<template>
  <div class="main">
    <!-- 搜索栏 -->
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="主题" prop="title">
        <el-input
          v-model="searchFormParams.title"
          placeholder="请输入主题"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="信息来源" prop="infoSource">
        <el-select
          v-model="searchFormParams.infoSource"
          placeholder="请选择信息来源"
          clearable
          class="!w-[200px]"
        >
          <el-option label="风险识别" value="1" />
          <el-option label="隐患排查" value="2" />
          <el-option label="安全质量检查" value="3" />
          <el-option label="安全专项检查" value="4" />
          <el-option label="法定自查" value="5" />
          <el-option label="自愿报告" value="6" />
          <el-option label="安全预警" value="7" />
          <el-option label="应急案例" value="8" />
          <el-option label="通知公告" value="9" />
          <el-option label="审核审计" value="10" />
          <el-option label="外部检查" value="11" />
        </el-select>
      </el-form-item>


      <el-form-item label="责任单位" prop="deptId">
        <el-cascader
          v-model="searchFormParams.dutyDeptId"
          :options="deptTree"
          :props="{
        value: 'value',
        label: 'label',
        emitPath: false,
        checkStrictly: true
          }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="处理单位" prop="acceptDeptId">
        <el-cascader
          v-model="searchFormParams.acceptDeptId"
          :options="deptTree"
          :props="{
        value: 'value',
        label: 'label',
        emitPath: false,
        checkStrictly: true
          }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>


      <el-form-item label="状态" prop="status">
        <el-select
          v-model="searchFormParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-[200px]"
        >
          <el-option label="待接收" value="0" />
          <el-option label="待建模" value="1" />
          <el-option label="已关闭" value="2" />
          <el-option label="已建模-问题待提交" value="3" />
          <el-option label="已建模-已提交问题" value="4" />
          <el-option label="未建模-已提交问题" value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="报告人" prop="discoverUserName">
        <el-input
          v-model="searchFormParams.discoverUserName"
          placeholder="请输入报告人"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="发现时间">
        <el-date-picker
          class="!w-[240px]"
          v-model="timeRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch(tableRef)"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="handleReset"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>



    <!-- table bar 包裹  table -->
    <PureTableBar title="安全信息列表" :columns="columns" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog('add')"
        >
          手动上报
        </el-button>
        <el-button
          type="danger"
          :icon="useRenderIcon(Delete)"
          @click="handleBulkDeleteWithPermission(tableRef)"
        >
          批量删除
        </el-button>
<!--        <el-button-->
<!--          type="primary"-->
<!--          @click="CommonUtils.exportExcel(columns, dataList, '安全信息列表')"-->
<!--        >单页导出</el-button-->
<!--        >-->
<!--        <el-button type="primary" @click="exportAllExcel">全部导出</el-button>-->
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getReportList"
          @page-current-change="getReportList"
          @sort-change="onSortChanged"
          @selection-change="
            rows => (multipleSelection = rows.map(item => item.reportId))
          "
        >
          <!-- 新增 infoDescribe 插槽 -->
          <template #infoDescribe="{ row }">
            <div
              class="detail-value"
              @click="openDetail(row)"
              style="cursor: pointer; color: var(--el-color-primary);"
            >
              {{ decodeBase64withoutLab(row.infoDescribe || "") }}
            </div>
          </template>
          <!-- 添加关联整改通知列内容 -->
          <template #relatedReformCode="{ row }">
            <el-link
              v-if="row.relatedReformCode && row.relatedReformCode !== ''"
              type="primary"
              @click="handleReformClick(row)"
              style="cursor: pointer"
            >
              {{ row.relatedReformCode }}
            </el-link>
            <span v-else>无</span>
          </template>


          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="info"
              :size="size"
              :icon="useRenderIcon(Detail)"
              @click="openDetail(row)"
            >
              详情
            </el-button>
            <!-- 当 status 为 0 时显示接收按钮 -->
            <el-button
              v-if="row.status === '0'"
              class="reset-margin"
              link
              type="success"
              :size="size"
              :icon="useRenderIcon(import('@iconify-icons/ep/check'))"
              @click="handleReceive(row)"
            >
              <el-icon><Bottom /></el-icon>

              接收
            </el-button>
            <el-button
              v-if="row.status === '0'"
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(import('@iconify-icons/ep/check'))"
              @click="handleForward(row)"
            >
              <el-icon><Right /></el-icon>

              转发
            </el-button>
            <!-- 当 status 为 1 时显示关联已有模型和风险建模按钮 -->
            <template v-if="row.status === '1'">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(Link)"
                @click="linkExistingModel(row)"
              >
                关联已有模型
              </el-button>
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(ModelBuild)"
                @click="riskModeling(row)"
              >
                风险建模
              </el-button>
            </template>
            <!-- 当 status 为 3 时显示问题提交按钮 -->
            <el-button
              v-if="row.status == '1' || row.status == '3'"
              class="reset-margin"
              link
              type="warning"
              :size="size"
              @click="handleSubmit(row)"
            >
              <el-icon><Top /></el-icon>

              直接整改
            </el-button>
            <el-popconfirm
              :title="`是否确认删除编号为${row.reportId}的这个安全信息`"
              @confirm="handleDelete(row)"
            >
              <template #reference>

              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <report-detail-modal
      v-model="detailVisible"
      :row="detailRow"
    />
    <report-form-modal
      v-model="modalVisible"
      :type="opType"
      :row="opRow"
      @success="getReportList"
      :deptTree=deptTree
    />

    <report-forward-modal
      v-model="forwardDialogVisible"
      :row="forwardRow"
      :deptTree="deptTree"
      @success="getReportList"
    />

    <ReportSubmitModal
      v-model="submitDialogVisible"
      :row="submitRow"
      @success="getReportList"
    />

    <!-- 新增 inspectionCheck 详情弹窗 -->
    <InspectionCheckDetailModal
      v-model="inspectionCheckDetailVisible"
      :row="inspectionCheckDetailData"
      @success="onSearch"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
